package com.zyh.controller;

import com.zyh.entity.Address;
import com.zyh.entity.User;
import com.zyh.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("address")
public class AddressController {
    @Autowired
    private AddressService addressService;
    @Autowired
    private ModelAndView mav;

    @RequestMapping("selectByUser")
    public ModelAndView selectByUser(HttpSession session, Integer state){
        User user =(User) session.getAttribute("user");

        if(user!=null){
            List<Address> addresses = addressService.selectByUserId(user.getId());
            mav.addObject("addresses",addresses);
            if(state==null){
                mav.setViewName("/address/my_address.jsp");
            }else{
                mav.setViewName("/order/address_form.jsp");
            }
        }else{
            mav.setViewName("redirect:/user/login_form.jsp");
        }
        return mav;
    }

    @RequestMapping("updateSelected")
    /*
    * 将对应的地址设置为默认地址，并同时将当前的默认地址设置为非默认地址
    *
    * */
    public ModelAndView updateSelected(HttpSession session,Integer aId){
        User user =(User) session.getAttribute("user");
        if(user!=null){
            Integer uId = user.getId();//获取已登陆的用户ID
            addressService.updateByUid(uId);//设置为非默认地址
            addressService.updateByAddrId(aId);//设置为默认地址
            mav.setViewName("/address/selectByUser.do");//转发到查找用户所有地址
        }else{
            mav.setViewName("redirect:/user/login_form.jsp");//重定向到登录jsp
        }
        return mav;
    }

    @RequestMapping("deleteAddr")
    /*
    * 将对应ID地址的删除状态设为1
    * 参数aId:jsp传过来的对应地址ID
    * */
    public ModelAndView deleteAddr(HttpSession session,Integer aId){
        addressService.updateDeleteState(aId);
        mav.setViewName("/address/selectByUser.do");
        return mav;
    }

    @RequestMapping("insert")
    public ModelAndView insert(HttpSession session,Address address){
        User user =(User) session.getAttribute("user");
        address.setUid(user.getId());
        addressService.insert(address);
        mav.setViewName("/address/selectByUser.do");
        return mav;
    }
}
